<script lang="jsx" setup>
import { computed, nextTick, onMounted, ref } from 'vue';
import dayjs from 'dayjs';
import { useRoute } from 'vue-router';
import { Modal as antModal, message } from 'ant-design-vue';
import Table from '@/components/common/table.vue';
import { downLoadExcel, get, post, put } from '@/service/api/api';
import { getServiceBaseURL } from '@/utils/service';
import CommonSearch from '../common-search.vue';
import Modal from '../modal.vue';
import AddForm from './add-form.vue';

const baseUrl = import.meta.env.VITE_SERVICE_BASE_URL;
const route = useRoute();

const props = defineProps({
  searchFormList: {
    type: Array,
    default: () => []
  },
  searchParam: {
    type: Object,
    default: () => null
  },
  column: {
    type: Array,
    default: () => []
  },
  pageSizeOptions: {
    type: Array,
    default: () => ['50', '100', '200', '300', '500']
  },
  getSearchParams: {
    type: Function,
    default: () => null
  },
  tableKey: {
    type: String,
    default: () => 'id'
  },
  canRowDblclick: {
    type: Boolean,
    default: true
  },
  scroll: {
    type: Object,
    default: () => {
      return { x: 2000, y: 'auto' };
    }
  },
  url: {
    type: String,
    default: () => null
  },
  isInitGetData: {
    type: Boolean,
    default: () => true
  },
  // btnAuth: {
  //   type: Object,
  //   default: () => {
  //     return {
  //       add: null, // 新增权限
  //       edit: null, // 编辑修改权限
  //       del: null, // 删除权限
  //       foremanAudit: null, // 领班审核权限
  //       supervisorAudit: null, // 主管审核权限
  //       withdrawTrial: null, // 撤审权限
  //       download: null // 导出
  //     };
  //   }
  // },
  otherBtnList: {
    type: Array,
    default: () => []
  },
  formId: {
    type: [String, Number],
    default: () => null
  },
  downLoadUrl: {
    type: String,
    default: () => '/qms/agv/Exporter/exportExcel'
  },
  addUrl: {
    type: String,
    default: () => '/qms/single/singleTestStardardBoard/add'
  },
  editUrl: {
    type: String,
    default: () => '/qms/single/singleTestStardardBoard/update'
  },
  delUrl: {
    type: String,
    default: () => '/qms/single/singleTestStardardBoard/deleteBatch'
  },
  topFormList: {
    type: Array,
    default: () => []
  },
  bottomList: {
    type: Array,
    default: () => []
  },
  modalTableColumn: {
    type: Array,
    default: () => []
  },
  modalTableKey: {
    type: String,
    default: () => 'id'
  },
  modalGetTableDataUrl: {
    type: String,
    default: null
  },
  modalTableScroll: {
    type: Object,
    default: () => {
      return { x: 'auto', y: 'auto' };
    }
  },
  modalTableTitle: {
    type: String,
    default: '质量项目'
  },
  transfromRowData: {
    type: Function,
    default: null
  },
  routeName: {
    type: String,
    default: null
  },
  modalHeight: {
    type: String,
    default: () => '80vh'
  },
  modalWidth: {
    type: String,
    default: () => '70vw'
  },
  modalAddTableKey: {
    type: String,
    default: null
  },
  modalAddTableDataFilter: {
    type: Boolean,
    default: true
  },
  modleSearchUrlObj: {
    type: Object,
    default: () => {
      return {
        moduleNo: '/rcerp/agv/erp/findByModuleNo'
      };
    }
  },
  addMethod: {
    type: String,
    default: 'post'
  },
  editMethod: {
    type: String,
    default: 'post'
  },
  delMethod: {
    type: String,
    default: 'post'
  },
  isCustomAdd: {
    type: Boolean,
    default: false
  },
  modalDivider: {
    type: String,
    default: null
  },
  modalGetTableUrlSuffix: {
    type: Object,
    default: null
  },
  showTableToolsBtn: {
    type: Boolean,
    default: true
  },
  // 是否显示IPQC审核按钮
  showIPQCExamine: {
    type: Boolean,
    default: false
  },
  iPQCExamineText: {
    type: String,
    default: () => 'QA审核'
  },
  addUseRowData: {
    type: Boolean,
    default: false
  },
  showDownload: {
    type: Boolean,
    default: true
  },
  isProductionTable: {
    type: Boolean,
    default: true
  },
  pageSize: {
    type: Number,
    default: 200
  },
  createByKey: {
    type: String,
    default: 'operator'
  },
  addSuccessColse: {
    type: Boolean,
    default: true
  }
});

const btnAuth = ref({
  add: props.routeName ? `${props.routeName}:add` : 'single-test-stardard-board:add',
  edit: props.routeName ? `${props.routeName}:edit` : 'single-test-stardard-board:edit', // 编辑修改权限
  del: props.routeName ? `${props.routeName}:del` : 'single-test-stardard-board:del', // 删除权限
  IPQCExamine: props.routeName ? `${props.routeName}:IPQCExamine` : 'single-test-stardard-board:IPQCExamine', // IPQC审核权限
  foremanAudit: props.routeName ? `${props.routeName}:foremanAudit` : 'single-test-stardard-board:foremanAudit', // 领班审核权限
  supervisorAudit: props.routeName
    ? `${props.routeName}:supervisorAudit`
    : 'single-test-stardard-board:supervisorAudit', // 主管审核权限
  withdrawTrial: props.routeName ? `${props.routeName}:withdrawTrial` : 'single-test-stardard-board:withdrawTrial', // 撤审权限
  download: props.routeName ? `${props.routeName}:download` : 'single-test-stardard-board:download' // 导出
});
console.log('page props :>> ', props);
console.log('btnAuth :>> ', btnAuth);

const searchFormList = props.searchFormList.map(item => {
  if (item.type === 'dateRangePicker' && item.showTime === undefined) {
    item.showTime = true;
  }
  return {
    ...item
  };
});

const emit = defineEmits([
  'tableSelectChange',
  'tableRowClick',
  'tableRowDblclick',
  'modalClose',
  'openModal',
  'addSuccess'
]);

const commonSearchRef = ref(null);
const searchParams = ref(props.searchParam);

const searchData = computed(() => {
  if (!props.getSearchParams()) {
    const params = {};
    props.searchFormList.forEach(item => {
      if (item.type === 'dateRangePicker' && searchParams.value.time?.[0]) {
        params.startTime = dayjs(searchParams.value.time[0]).format(
          item.showTime ? 'YYYY-MM-DD HH:mm:ss' : 'YYYY-MM-DD'
        );
        params.endTime = dayjs(searchParams.value.time[1]).format(item.showTime ? 'YYYY-MM-DD HH:mm:ss' : 'YYYY-MM-DD');
      } else {
        params[item.key] = searchParams.value[item.key];
      }
    });
    delete params.time;
    return params;
  }
  return {
    ...props.getSearchParams()
  };
});

const tableRef = ref(null);
function search() {
  tableRef.value.getData(1);
}

function submitSearch() {
  tableRef.value.getData();
}

function reset() {
  nextTick(() => {
    search();
  });
}

const tableSelect = ref([]);

function tableSelectChange(val) {
  emit('tableSelectChange', val);
  tableSelect.value = val;
}

const operateType = ref('add');
const visible = ref(false);
const addFormRef = ref(null);
const currentRow = ref(null);
const modleAddLoading = ref(false);

function handleShowModal(type, row) {
  if (!props.isCustomAdd) {
    currentRow.value = row;
    operateType.value = type;
    visible.value = true;
  }

  emit('openModal', {
    currentRow: props.addUseRowData ? tableSelect.value?.[0] || null : row,
    operateType: type
  });
}

async function handleOk(type) {
  const params = {
    ...addFormRef.value.personModle,
    ...addFormRef.value.model
  };
  await addFormRef.value.validate();
  let pro;
  let url = props.addUrl;
  let messageText = '新增成功';
  if (props.modalTableColumn.length && props.modalGetTableDataUrl && props.modalAddTableKey) {
    if (props.modalAddTableDataFilter) {
      params[props.modalAddTableKey] = addFormRef.value.tableData.filter(item => item.number);
    } else {
      params[props.modalAddTableKey] = addFormRef.value.tableData;
    }
  }
  if (type === 'add') {
    if (props.addMethod.toLocaleLowerCase() === 'post') {
      pro = post(url, params);
    } else {
      pro = put(url, params);
    }
  }
  if (type === 'edit') {
    params.id = tableSelect.value[0][props.tableKey];
    url = props.editUrl;
    messageText = '修改成功';
    if (props.editMethod.toLocaleLowerCase() === 'post') {
      pro = post(url, params);
    } else {
      pro = put(url, params);
    }
  }

  modleAddLoading.value = true;
  delete params.undefined;
  pro
    .then(({ data, error, msg }) => {
      if (!error) {
        message.success(messageText);
        tableRef.value.tableSelectChange([]);
        if (type === 'edit') {
          submitSearch();
          handleClose();
        } else {
          commonSearchRef.value.formReset();
          if (props.addSuccessColse) {
            handleClose();
          }
        }
        emit('addSuccess', {
          data,
          error,
          msg
        });
      }
    })
    .finally(() => {
      modleAddLoading.value = false;
    });
}

function handleClose() {
  visible.value = false;
  emit('modalClose');
}

function tableRowClick(val) {
  emit('tableRowClick', val);
}

function tableRowDblclick(val) {
  emit('tableRowDblclick', val);
  if (!props.canRowDblclick) return;
  handleShowModal('look', val);
}

// 导出报表
function exportExcel() {
  const fileName = `${route.meta.title}${dayjs().format('YYYY-MM-DD HH:mm:ss')}.xlsx`;
  const params = {
    ...searchData.value,
    formId: props.formId
  };
  downLoadExcel(props.downLoadUrl, params, fileName);
}
// 审核
function handleApproval(state) {
  if (!tableSelect.value.length) {
    message.error('请选择要审核的数据!');
  }
  const params = {
    formId: props.formId,
    list: tableSelect.value.map(item => item.id),
    state
  };
  antModal.confirm({
    title: '确定进行批量审核吗?',
    onOk: () => {
      // return instance.post('/agv/Exporter/updateBatch',data);
      post('/qms/agv/Exporter/updateBatch', params).then(({ data, error }) => {
        if (!error) {
          message.success('批量审核成功!');
          submitSearch();
          tableRef.value.tableSelectChange([]);
        }
      });
    },
    onCancel: () => {}
  });
}
// 删除
function delData() {
  if (!tableSelect.value.length) return;
  antModal.confirm({
    title: `确定删除${tableSelect.value.length}条数据吗?`,
    onOk: () => {
      let pro;
      if (props.delMethod.toLocaleLowerCase() === 'post') {
        pro = post(props.delUrl, tableSelect.value);
      } else {
        pro = put(props.delUrl, tableSelect.value);
      }
      pro.then(({ data, error }) => {
        if (!error) {
          message.success('删除成功!');
          commonSearchRef.value.formReset();
          tableRef.value.tableSelectChange([]);
        }
      });
    },
    onCancel: () => {}
  });
}

function handleFallback() {
  if (!tableSelect.value.length) {
    message.error('请选择要撤审的数据!');
    return;
  }
  const id = tableSelect.value[0].id;
  antModal.confirm({
    title: '确定进行撤审吗?',
    onOk: () => {
      get(`/qms/agv/Exporter/Fallback?formId=${props.formId}&id=${id}`).then(({ data, error }) => {
        if (!error) {
          message.success('撤审成功!');
          // commonSearchRef.value.formReset();
          tableRef.value.tableSelectChange([]);
          submitSearch();
        }
      });
    },
    onCancel: () => {}
  });
}

function delModalTableRow(row) {
  addFormRef.value.delRow(row);
}

function getModalTableData() {
  return addFormRef.value.tableData;
}

function getModalModel() {
  return {
    topModel: addFormRef.value.model,
    bottomModel: addFormRef.value.personModle
  };
}

function resetGetData() {
  commonSearchRef.value.formReset();
  tableRef.value.tableSelectChange([]);
}

const column = ref(props.column);

// 目前列表上没有创建人列，需要在此处添加 现在需要统一添加
function addCreateFounderColumn() {
  if (props.isProductionTable) {
    column.value.splice(-2, 0, {
      key: 'create-founder',
      dataIndex: 'create-founder',
      title: '创建人',
      width: 100,
      align: 'center',
      checked: true,
      ellipsis: true
    });
  }
}

addCreateFounderColumn();

defineExpose({
  delModalTableRow,
  getModalTableData,
  getModalModel,
  resetGetData
});
</script>

<template>
  <div class="jl-main-page min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <CommonSearch
      ref="commonSearchRef"
      v-model:searchParams="searchParams"
      :form-list="searchFormList"
      :is-search="true"
      @search="search"
      @reset="reset"
    >
      <template #search>
        <slot name="search"></slot>
      </template>
      <template #other>
        <slot name="other"></slot>
      </template>
    </CommonSearch>
    <Table
      ref="tableRef"
      v-model:searchParams="searchData"
      :column="column"
      :page-size-options="props.pageSizeOptions"
      :page-size="props.pageSize"
      :row-key="props.tableKey"
      :scroll="props.scroll"
      :is-init-get-data="props.isInitGetData"
      :url="props.url"
      :is-production-table="props.isProductionTable"
      :create-by-key="props.createByKey"
      @table-select-change="tableSelectChange"
      @table-row-click="tableRowClick"
      @table-row-dblclick="tableRowDblclick"
    >
      <template #tableTitle>
        <template v-if="props.showTableToolsBtn">
          <AButton
            v-hasAuth="[btnAuth.add]"
            type="primary"
            size="small"
            ghost
            class="mini-btn mr-8px"
            @click="handleShowModal('add', null)"
          >
            <template #icon>
              <icon-ic-round-add class="align-sub text-icon" />
            </template>
            <span class="ml-3px">新增</span>
          </AButton>
          <AButton
            v-hasAuth="[btnAuth.edit]"
            type="primary"
            size="small"
            ghost
            class="mini-btn mr-8px"
            :disabled="tableSelect.length != 1"
            @click="handleShowModal('edit', tableSelect[0])"
          >
            <template #icon>
              <icon-ic-round-edit class="align-sub text-icon" />
            </template>
            <span class="ml-3px">修改</span>
          </AButton>
          <AButton
            v-hasAuth="[btnAuth.del]"
            type="primary"
            danger
            size="small"
            ghost
            class="mini-btn mr-8px"
            :disabled="!tableSelect.length"
            @click="delData"
          >
            <template #icon>
              <icon-ic-round-delete class="align-sub text-icon" />
            </template>
            <span class="ml-3px">删除</span>
          </AButton>
          <AButton
            v-if="props.showIPQCExamine"
            v-hasAuth="[btnAuth.IPQCExamine]"
            type="primary"
            size="small"
            ghost
            class="mini-btn mr-8px"
            :disabled="!tableSelect.length"
            @click="handleApproval(4)"
          >
            <template #icon>
              <span class="iconfont icon-shenhe" style="font-size: 14px"></span>
            </template>
            <span class="ml-3px">{{ props.iPQCExamineText }}</span>
          </AButton>
          <AButton
            v-hasAuth="[btnAuth.foremanAudit]"
            type="primary"
            size="small"
            ghost
            class="mini-btn mr-8px"
            :disabled="!tableSelect.length"
            @click="handleApproval(2)"
          >
            <template #icon>
              <span class="iconfont icon-shenhe" style="font-size: 14px"></span>
            </template>
            <span class="ml-3px">领班审核</span>
          </AButton>
          <AButton
            v-hasAuth="[btnAuth.supervisorAudit]"
            type="primary"
            size="small"
            ghost
            class="mini-btn mr-8px"
            :disabled="!tableSelect.length"
            @click="handleApproval(3)"
          >
            <template #icon>
              <span class="iconfont icon-shenhe" style="font-size: 14px"></span>
            </template>
            <span class="ml-3px">主管审核</span>
          </AButton>
          <AButton
            v-hasAuth="[btnAuth.withdrawTrial]"
            type="primary"
            size="small"
            ghost
            class="mini-btn mr-8px"
            :disabled="tableSelect.length != 1"
            @click="handleFallback"
          >
            <template #icon>
              <span class="iconfont icon-cheshenanniu" style="font-size: 14px"></span>
            </template>
            <span class="ml-3px">撤审</span>
          </AButton>
          <AButton
            v-if="props.showDownload"
            v-hasAuth="[btnAuth.download]"
            type="primary"
            size="small"
            ghost
            class="mini-btn mr-8px"
            @click="exportExcel"
          >
            <template #icon>
              <icon-ic-round-download class="align-sub text-icon" />
            </template>
            <span class="ml-3px">导出</span>
          </AButton>
        </template>
        <template v-for="(item, index) in props.otherBtnList" :key="index">
          <AButton
            v-if="!item.isUpload"
            v-hasAuth="[item.auth]"
            type="primary"
            size="small"
            ghost
            class="mini-btn mr-8px"
            @click="
              () => {
                item.handleClick && item.handleClick(item, tableSelect, searchParams);
              }
            "
          >
            <template #icon>
              <template v-if="item.iconType == 1">
                <SvgIcon :icon="item.icon" class="text-icon" />
              </template>
              <template v-if="item.iconType == 2">
                <SvgIcon :local-icon="item.icon" class="text-icon" />
              </template>
              <template v-if="item.iconType == 3">
                <span :class="`iconfont ${item.icon}`" style="font-size: 18px"></span>
              </template>
            </template>
            {{ item.name }}
          </AButton>
          <template v-else>
            <AUpload
              v-model:file-list="item.fileList"
              v-hasAuth="[item.auth]"
              class="my-upload"
              name="file"
              :action="`http://192.168.188.255:9999/prod-api${item.url}`"
              @change="item.handleChange"
            >
              <AButton type="primary" size="small" ghost class="mini-btn mr-8px">
                {{ item.name }}
                <template #icon>
                  <icon-ic-round-upload class="align-sub text-icon" />
                </template>
              </AButton>
            </AUpload>
          </template>
        </template>
      </template>
    </Table>

    <Modal
      v-model:visible="visible"
      :title="`${route.meta.title}${{ add: '新增', edit: '编辑', look: '明细' }[operateType]}`"
      :height="props.modalHeight"
      :width="props.modalWidth"
      :destroy-on-close="true"
      :centered="true"
      @close="handleClose"
    >
      <AddForm
        ref="addFormRef"
        :row-data="currentRow"
        :operate-type="operateType"
        :top-form-list="props.topFormList"
        :bottom-list="props.bottomList"
        :transfrom-row-data="props.transfromRowData"
        :column="props.modalTableColumn"
        :table-key="props.modalTableKey"
        :get-table-data-url="props.modalGetTableDataUrl"
        :scroll="props.modalTableScroll"
        :search-url-obj="props.modleSearchUrlObj"
        :divider="props.modalDivider"
        :get-table-url-suffix="props.modalGetTableUrlSuffix"
        :table-title="props.modalTableTitle"
      />
      <template #footer>
        <div class="modal-footer">
          <AButton v-if="operateType == 'add'" type="primary" :loading="modleAddLoading" @click="handleOk('add')">
            保 存
          </AButton>
          <AButton v-if="operateType == 'edit'" type="primary" :loading="modleAddLoading" @click="handleOk('edit')">
            修 改
          </AButton>
          <AButton @click="handleClose">关 闭</AButton>
        </div>
      </template>
    </Modal>
    <slot></slot>
  </div>
</template>

<style lang="scss" scoped>
.my-upload {
  height: 25px;

  :deep(.ant-upload-list) {
    display: none;
  }
}
</style>
